const fs = require('fs');
const path = require('path');
const { pinyin } = require('pinyin-pro');

// 获取当前目录
const currentDirectory = __dirname;

// 将中文名称转换为拼音
function toPinyin(name) {
    return pinyin(name, { toneType: 'none', type: 'array' }).join('');
}

// 递归读取目录
function readDirectory(directory) {
    return new Promise((resolve, reject) => {
        fs.readdir(directory, (err, items) => {
            if (err) {
                return reject(err);
            }

            let results = [];
            let promises = items.map(item => {
                const fullPath = path.join(directory, item);
                const pinyinName = toPinyin(item);
                const newFullPath = path.join(directory, pinyinName);

                return new Promise((res, rej) => {
                    fs.stat(fullPath, (err, stats) => {
                        if (err) {
                            return rej(err);
                        }

                        const renamePromise = new Promise((renameRes, renameRej) => {
                            if (fullPath !== newFullPath) {
                                fs.rename(fullPath, newFullPath, (renameErr) => {
                                    if (renameErr) {
                                        return renameRej(renameErr);
                                    }
                                    renameRes();
                                });
                            } else {
                                renameRes();
                            }
                        });

                        renamePromise.then(() => {
                            if (stats.isDirectory()) {
                                readDirectory(newFullPath).then(subResults => {
                                    results.push({
                                        type: 'directory',
                                        name: pinyinName,
                                        path: newFullPath,
                                        contents: subResults
                                    });
                                    res();
                                }).catch(rej);
                            } else {
                                results.push({
                                    type: 'file',
                                    name: pinyinName,
                                    path: newFullPath
                                });
                                res();
                            }
                        }).catch(rej);
                    });
                });
            });

            Promise.all(promises).then(() => resolve(results)).catch(reject);
        });
    });
}

readDirectory(currentDirectory).then(results => {
    console.log(JSON.stringify(results, null, 2));
}).catch(err => {
    console.error('Error reading directory:', err);
});